# coding=utf-8


from models.albums import Albums
from models.article_comments import ArticleComments

from models.articles import Articles
from models.base import db
from models.categories import Categories
from models.images import Images
from models.users import Users
from models.version import Version


class DbInit(object):
    def __init__(self):
        db.connect()

        tables = [
            Albums,
            ArticleComments,
            Articles,
            Categories,
            Images,
            Users,
            Version,
        ]

        if not Version.table_exists():
            db.create_tables(tables)

        self.version, _ = Version.get_or_create(description="0.1")
        self.default_thumbnail = ""
        # self.default_thumbnail = base64.b64encode(
        #     buffer(Imaging.default_thumbnail()))

        self.sys_categories, _ = Categories.get_or_create(
            name='系统分类',
            description='初始父类!',
            thumbnail=self.default_thumbnail,
        )
        self.article_categories = Categories.create(
            name='文章',
            description='文章',
            thumbnail=self.default_thumbnail,
            parent=self.sys_categories
        )

        self.admin, _ = Users.get_or_create(
            name='admin',
            cellphone='19999999999',
            email='admin@webpy.cn',
            address='陕西西安',
            birthday='2020.9',
            password='3981c2d8a3917de70be4ff59e2f68b30',
            gender=0,
            description='系统管理员!',
            avatar=self.default_thumbnail
        )

        self.sys_album, _ = Albums.get_or_create(
            name='系统专辑',
            description='系统专辑!',
            thumbnail=self.default_thumbnail,
            owner=self.admin
        )

        self.sys_image, _ = Images.get_or_create(
            description='系统图片!',
            thumbnail=self.default_thumbnail,
            owner=self.admin,
            album=self.sys_album,
            uuid='default'
        )

    def print_trace_log(self):
        print('Database Version: %s' % self.version.description)
        print('Administrator: name=%s, cellphone=%s, email=%s' % (self.admin.name,
                                                                self.admin.cellphone,
                                                                self.admin.email))
        print('Predefined System Album: name=%s, desc=%s' % (
        self.sys_album.name, self.sys_album.description))
        print('Predefined System Image: uuid=%s, desc=%s' % (
        self.sys_image.uuid, self.sys_image.description))


def init():
    db_init = DbInit()
    db_init.print_trace_log()


if __name__ == '__main__':
    db_init = DbInit()
    db_init.print_trace_log()
